var flagMap = false,
    flagUnit = false,
    flagDistrict = false,
    flagBuilding = false;

var unit = null;

minemap.accessToken = 'eeea35fb6c984047bb19e25463ee18e5';
minemap.solution = 3990;
var map = new minemap.Map({
    container: 'map',
    style: "//minedata.cn/service/solu/style/id/3990",
    center: [113.9306, 22.5460],
    zoom: 15,
    pitch: 0,
    maxZoom: 17,
    minZoom: 12,
});

var popup = new minemap.Popup({
    closeButton: false,
    offset: [0, -12],
    fontSize: '10px',
    paddingTop: '0'
});

var popup1 = new minemap.Popup({
    closeButton: false,
    offset: [0, -12],
    fontSize: '10px',
    paddingTop: '0'
});



var filterEl = document.getElementById('feature-filter');
var listingEl = document.getElementById('feature-listing');
var detailEl = document.getElementById('feature-detail');
var bulidingDetail = document.getElementById('building-detail');

var detailMainName = detailEl.getElementsByClassName('detail-mainName')[0];
var detailSubName = detailEl.getElementsByClassName('detail-subName')[0];
var detailArea = detailEl.getElementsByClassName('detail-area')[0];
var detailAddress = detailEl.getElementsByClassName('detail-address')[0];

var buildingName = bulidingDetail.getElementsByClassName('building-name')[0];
var buildingImgContainer = bulidingDetail.getElementsByClassName('building-img')[0];
var buildingUnitContainer = bulidingDetail.getElementsByClassName('unit-container')[0];

var carousel = null;

var selectId = '';

var districtGeojson = {
    "type": "FeatureCollection",
    "features": []
};
var districtPolygonGeojson = {
    "type": "FeatureCollection",
    "features": []
};
var districtGateGeojson = {
    "type": "FeatureCollection",
    "features": []
};
var buildingGeojson = {
    "type": "FeatureCollection",
    "features": []
};
var buildingUnit = {};

map.on('load', function () {
    // flagMap = true;
    var device1 = {
        buildingImg: './data1/poi_code_200103_16@2.png',
        buildingImgSelect: './data1/poi_code_200103_16@2.png',
        entry: './data1/poi_door_16@2.png',
        districtImg: './data1/poi_code_120201_16@2.png'
    }
    var device2 = {
        buildingImg: './data1/poi_code_200103_16@2.png',
        buildingImgSelect: './data1/poi_code_200103_16@2.png',
        entry: './data1/poi_door_16@2.png',
        districtImg: './data1/poi_code_120201_16@2.png'
    }

    var device = null;
    if (window.devicePixelRatio == 1) {
        device = device1;
    } else {
        device = device2;
    }

    // if (flagMap && flagUnit && flagDistrict && flagBuilding) {
    //     init();
    // }

    var districtImgFlag = false;
    var buildingImgFlag = false;
    var buildingImgSelectFlag = false;
    var gateImgFlag = false;

    var districtImg = new Image();
    districtImg.src = device.districtImg;
    districtImg.onload = function () {
        map.addImage('myIcom-district', districtImg);
        districtImgFlag = true;
        if(districtImgFlag && buildingImgFlag && buildingImgSelectFlag && gateImgFlag) {
            flagMap = true;
            if (flagMap && flagUnit && flagDistrict && flagBuilding) {
                init();
            }
        }
        // map.addLayer({
        //     "id": 'districtNameIcon',
        //     "type": "symbol",
        //     "source": "districtSource",
        //     'layout': {
        //         "icon-image": "myIcom-district",
        //         'icon-size': 0.7,
        //     },
        //     filter: ['in', '$type', 'Point'],
        //     minzoom: 12,
        //     maxzoom: 16
        // });
    }

    var gateImg = new Image();
    gateImg.src = device.entry;
    gateImg.onload = function () {
        map.addImage('myIcom-gate', gateImg);
        gateImgFlag = true;
        if(districtImgFlag && buildingImgFlag && buildingImgSelectFlag && gateImgFlag) {
            flagMap = true;
            if (flagMap && flagUnit && flagDistrict && flagBuilding) {
                init();
            }
        }

        // map.addImage('myIcom-gate', gateImg, {pixelRatio: 1});
        // map.addLayer({
        //     "id": 'districtGate',
        //     "type": "symbol",
        //     "source": "districtGateSource",
        //     'layout': {
        //         "icon-image": "myIcom-gate",
        //         'icon-size': 0.7
        //     },
        //     filter: ['in', '$type', 'Point'],
        //     minzoom: 16,
        //     maxzoom: 18
        // });
    }

    var buildingImg = new Image();
    buildingImg.src = device.buildingImg;
    buildingImg.onload = function () {
        map.addImage('myIcom-building', buildingImg);
        // map.addImage('myIcom-building', buildingImg, {pixelRatio: 1});
        buildingImgFlag = true;
        if(districtImgFlag && buildingImgFlag && buildingImgSelectFlag && gateImgFlag) {
            flagMap = true;
            if (flagMap && flagUnit && flagDistrict && flagBuilding) {
                init();
            }
        }
        // map.addLayer({
        //     "id": 'buildingIcon',
        //     "type": "symbol",
        //     "source": "bulidingSource",
        //     'layout': {
        //         "icon-image": "myIcom-building",
        //         'icon-size': 0.7,
        //         "icon-allow-overlap": false
        //     },
        //     filter: ['==', '楼栋所属楼盘ID', ''],
        //     minzoom: 16,
        //     maxzoom: 18
        // });
    }

    var buildingImgSelect = new Image();
    buildingImgSelect.src = device.buildingImgSelect;
    buildingImgSelect.onload = function () {
        map.addImage('myIcom-buildingSelect', buildingImgSelect);
        // map.addImage('myIcom-buildingSelect', buildingImgSelect, {pixelRatio: 1});
        buildingImgSelectFlag = true;
        if(districtImgFlag && buildingImgFlag && buildingImgSelectFlag && gateImgFlag) {
            flagMap = true;
            if (flagMap && flagUnit && flagDistrict && flagBuilding) {
                init();
            }
        }
        // map.addLayer({
        //     "id": 'buildingIconSelect',
        //     "type": "symbol",
        //     "source": "bulidingSource",
        //     'layout': {
        //         "icon-image": "myIcom-buildingSelect",
        //         'icon-size': 0.7,
        //         "icon-allow-overlap": true
        //     },
        //     filter: ['==', '楼栋ID', ''],
        //     minzoom: 16,
        //     maxzoom: 18
        // });
    }
});

getJson('./data1/building.json', function (data) {
    var building = JSON.parse(data);
    building.forEach(function (element) {
        buildingGeojson["features"].push({
            "geometry": {
                "type": "Point",
                "coordinates": [element["楼栋坐标JC02经度"], element["楼栋坐标JC02纬度"]]
            },
            "type": "Feature",
            "properties": {
                "楼栋ID": element["楼栋ID"],
                "楼栋所属楼盘ID": element["楼栋所属楼盘ID"],
                "楼栋所属楼盘主名称": element["楼栋所属楼盘主名称"],
                "楼栋主名称": element["楼栋主名称"],
                "楼栋别名": element["楼栋别名"],
                "楼栋照片": element["楼栋照片"],
                "coordinates": element["楼栋坐标JC02经度"] + ',' + element["楼栋坐标JC02纬度"]
            }
        });
    })
    flagBuilding = true;
    if (flagMap && flagUnit && flagDistrict && flagBuilding) {
        init();
    }
});

getJson('./data1/district.json', function (data) {
    var district = JSON.parse(data);
    var districtDom = {};
    district.forEach(function (element) {
        if (!districtDom[element["楼盘ID"]]) {
            districtDom[element["楼盘ID"]] = true;

            districtGeojson["features"].push({
                "geometry": {
                    "type": "Point",
                    "coordinates": element["小区中心点坐标JC02"].split(',')
                },
                "type": "Feature",
                "properties": {
                    "楼盘ID": element["楼盘ID"],
                    "楼盘主名": element["楼盘主名"],
                    "楼盘别名": element["楼盘别名"],
                    "行政区": element["行政区"],
                    "门牌号码": element["门牌号码"],
                    "coordinates": element["小区中心点坐标JC02"]
                }
            });

            districtPolygonGeojson["features"].push({
                "geometry": {
                    "type": "Polygon",
                    "coordinates": [element["小区边界坐标集合JC02"].split(',').map(function (data) {
                        return data.split(' ');
                    })]
                },
                "type": "Feature",
                "properties": {
                    "楼盘ID": element["楼盘ID"],
                    "楼盘主名": element["楼盘主名"],
                    "楼盘别名": element["楼盘别名"],
                    "行政区": element["行政区"],
                    "门牌号码": element["门牌号码"],
                    "coordinates": element["小区中心点坐标JC02"]
                }
            });
        }
        if (element["小区入口名称"]) {
            districtGateGeojson["features"].push({
                "geometry": {
                    "type": "Point",
                    "coordinates": [element["小区入口坐标JC02经度"], element["小区入口坐标JC02纬度"]]
                },
                "type": "Feature",
                "properties": {
                    "小区入口名称": element["小区入口名称"],
                    "楼盘主名": element["楼盘主名"]
                }
            });
        }
    });
    flagDistrict = true;
    if (flagMap && flagUnit && flagDistrict && flagBuilding) {
        init();
    }
});

getJson('./data1/unit.json', function (data) {
    unit = JSON.parse(data);
    unit.forEach(function (element) {
        if (buildingUnit[element['单元所属楼栋ID']]) {
            buildingUnit[element['单元所属楼栋ID']].push({
                '单元主名称': element['单元主名称'],
                '单元别名': element['单元别名'],
                '总层数': element['总层数'],
                '每层户数': element['每层户数'],
                '单元照片': element['单元照片']
            });
        } else {
            buildingUnit[element['单元所属楼栋ID']] = [{
                '单元主名称': element['单元主名称'],
                '单元别名': element['单元别名'],
                '总层数': element['总层数'],
                '每层户数': element['每层户数'],
                '单元照片': element['单元照片']
            }]
        }
    });
    flagUnit = true;
    if (flagMap && flagUnit && flagDistrict && flagBuilding) {
        init();
    }
});

function getJson(url, callback) {
    var xmlhttp = null;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttp != null) {
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4) {
                if (xmlhttp.status == 200) {
                    callback.call(null, xmlhttp.responseText);
                } else {
                    alert("Problem retrieving data:" + xmlhttp.statusText);
                }
            }
        }
        xmlhttp.open("GET", url, true);
        xmlhttp.send(null);
    } else {
        alert("Your browser does not support XMLHTTP.");
    }
}

function init() {
    map.addSource("districtSource", {
        "type": "geojson",
        "data": districtGeojson
    });

    map.addSource("districtGateSource", {
        "type": "geojson",
        "data": districtGateGeojson
    });

    map.addSource("districtPolygonSource", {
        "type": "geojson",
        "data": districtPolygonGeojson
    });

    map.addSource("bulidingSource", {
        "type": "geojson",
        "data": buildingGeojson
    });

    map.addLayer({
        'id': 'districtPolygon',
        'type': 'fill',
        'source': 'districtPolygonSource',
        'layout': {},
        'paint': {
            'fill-color': '#d0e9ff',
            'fill-opacity': 0.7
        },
        filter: ['in', '$type', 'Polygon'],
        minzoom: 16,
        maxzoom: 18
    });

    map.addLayer({
        'id': 'districtPolygonHighlight',
        'type': 'fill',
        'source': 'districtPolygonSource',
        'layout': {},
        'paint': {
            'fill-color': '#37c6c0',
            'fill-opacity': 0.4
        },
        filter: ['==', '楼盘ID', ''],
        minzoom: 16,
        maxzoom: 18
    });

    map.addLayer({
        'id': 'districtPolygonSelected',
        'type': 'fill',
        'source': 'districtPolygonSource',
        'layout': {},
        'paint': {
            'fill-color': '#1db0b8',
            'fill-opacity': 0.4
        },
        filter: ['==', '楼盘ID', ''],
        minzoom: 16,
        maxzoom: 18
    });

    map.addLayer({
        "id": 'districtNameText',
        "type": "symbol",
        "source": "districtSource",
        'layout': {
            "text-field": "{楼盘主名}",
            'text-size': 16
        },
        'paint': {
            "text-color": '#1c6c74',
        },
        filter: ['in', '$type', 'Point'],
        minzoom: 16,
        maxzoom: 18
    });

    map.addLayer({
        "id": 'districtGate',
        "type": "symbol",
        "source": "districtGateSource",
        'layout': {
            "icon-image": "myIcom-gate",  
            'icon-size': 0.7 
        },                    
        filter: ['in', '$type', 'Point'],
        minzoom: 16,
        maxzoom: 18
    });

    map.addLayer({
        "id": 'buildingIcon',
        "type": "symbol",
        "source": "bulidingSource",
        'layout': {
            "icon-image": "myIcom-building",  
            'icon-size': 0.7 ,
            "icon-allow-overlap": false
        },                    
        filter: ['==', '楼栋所属楼盘ID', ''],
        minzoom: 16,
        maxzoom: 18
    });

    map.addLayer({
        "id": 'districtNameIcon',
        "type": "symbol",
        "source": "districtSource",
        'layout': {
            "icon-image": "myIcom-district",  
            'icon-size': 0.7 ,
            "text-field": "{楼盘主名}",
            'text-size': 13,
            "text-anchor": "top",
            "text-offset": [0, 0.8]
        },
        'paint': {
            "text-color": '#0287e5',
        },                   
        filter: ['in', '$type', 'Point'],
        minzoom: 12,
        maxzoom: 16
    });

    map.addLayer({
        "id": 'buildingIconSelect',
        "type": "symbol",
        "source": "bulidingSource",
        'layout': {
            "icon-image": "myIcom-buildingSelect",  
            'icon-size': 0.7 ,
            "icon-allow-overlap": true
        },                    
        filter: ['==', '楼栋ID', ''],
        minzoom: 16,
        maxzoom: 18
    });

    map.on('mousemove', function (e) {
        var feature = map.queryRenderedFeatures(e.point, {
            layers: ['districtPolygon', 'districtNameIcon']
        });
        if (feature && feature[0]) {
            if (feature[0].layer.id === 'districtPolygon') {
                if (feature[0].properties['楼盘ID'] !== selectId) {
                    map.getCanvas().style.cursor = 'pointer';
                    map.setFilter('districtPolygonHighlight', ['==', '楼盘ID', feature[0].properties['楼盘ID']]);
                } else {
                    map.getCanvas().style.cursor = '';
                    map.setFilter('districtPolygonHighlight', ['==', '楼盘ID', '']);
                }
            }
            if (feature[0].layer.id === 'districtNameIcon' && feature[0].properties['门牌号码'].length) {
                map.getCanvas().style.cursor = 'pointer';
                popup.setLngLat(feature[0].properties.coordinates.split(','))
                    // .setText(feature[0].properties['门牌号码'])
                    .setHTML('<div class=\"popup-info\">' + feature[0].properties['门牌号码'] + '</div>')
                    .addTo(map);
            }
        } else {
            map.getCanvas().style.cursor = '';
            map.setFilter('districtPolygonHighlight', ['==', '楼盘ID', '']);
            popup.remove();
        }

        var featureBuilding = map.queryRenderedFeatures(e.point, {
            layers: ['buildingIcon']
        });
        if (featureBuilding && featureBuilding[0] && featureBuilding[0].properties['楼栋主名称'].length) {
            popup1.setLngLat(featureBuilding[0].properties.coordinates.split(','))
                // .setText(featureBuilding[0].properties['楼栋主名称'])
                .setHTML('<div class=\"popup-info\">' + featureBuilding[0].properties['楼栋主名称'] + '</div>')
                .addTo(map);
            map.getCanvas().style.cursor = 'pointer';
        } else {
            popup1.remove();
        }
    });

    map.on('click', function (e) {
        var feature = map.queryRenderedFeatures(e.point, {
            layers: ['districtPolygon', 'districtNameIcon']
        });
        if (feature && feature[0]) {
            // detailEl.innerHTML = '<p class=\'detail-mainName\'>' + feature[0].properties['楼盘主名'] + '</p>' +
            //                      (feature[0].properties['楼盘别名'] ? '<p class=\'detail-subName\'>' + feature[0].properties['楼盘别名'] + '</p>' : '') +
            //                      (feature[0].properties['行政区'] ? '<p class=\'detail-area\'>' + feature[0].properties['行政区'] + '</p>' : '') +
            //                      (feature[0].properties['门牌号码'] ? '<p class=\'detail-adress\'>' + feature[0].properties['门牌号码'] + '</p>' : '');
            detailMainName.innerHTML = feature[0].properties['楼盘主名'];
            if (feature[0].properties['楼盘别名']) {
                detailSubName.innerHTML = feature[0].properties['楼盘别名'];
                detailSubName.style.display = 'block';
            } else {
                detailSubName.style.display = 'none';
            }
            if (feature[0].properties['行政区']) {
                detailArea.innerHTML = feature[0].properties['行政区'];
                detailArea.style.display = 'inline-block';
            } else {
                detailArea.style.display = 'none';
            }
            if (feature[0].properties['门牌号码']) {
                detailAddress.innerHTML = feature[0].properties['门牌号码'];
                detailAddress.style.display = 'inline-block';
            } else {
                detailAddress.style.display = 'none';
            }

            listingEl.style.display = 'none';
            detailEl.style.display = 'block';
            map.flyTo({
                center: feature[0].properties.coordinates.split(','),
                zoom: 17
            });
            selectId = feature[0].properties['楼盘ID'];
            map.setFilter('districtPolygonSelected', ['==', '楼盘ID', feature[0].properties['楼盘ID']]);
            map.setFilter('buildingIcon', ['==', '楼栋所属楼盘ID', feature[0].properties['楼盘ID']]);
        }
        var featureBuilding = map.queryRenderedFeatures(e.point, {
            layers: ['buildingIcon']
        });
        if (featureBuilding && featureBuilding[0]) {
            // bulidingDetail.innerHTML = '<p class=\'building-name\'>' + featureBuilding[0].properties['楼栋主名称'] + '</p><p class=\'building-img\'>' 
            // + (featureBuilding[0].properties['楼栋照片']
            // ? '<img width=200 src='
            //   + featureBuilding[0].properties['楼栋照片'].split(';')[0] + '>'
            // : '<span class=\"noimg-big\">暂无图片</span>')
            // + '</p><p class=\'building-unitName\'>所属单元</p><div class=\'unit-container\'>'
            // + getUnitImg(buildingUnit[featureBuilding[0].properties['楼栋ID']])
            // + '</div>'
            buildingName.innerHTML = featureBuilding[0].properties['楼栋主名称'];
            if (featureBuilding[0].properties['楼栋照片']) {
                if (featureBuilding[0].properties['楼栋照片'].indexOf(';') < 0) {
                    buildingImgContainer.innerHTML = '<img width=200 src=' + featureBuilding[0].properties['楼栋照片'] + '>';
                } else {
                    buildingImgContainer.innerHTML = '';
                    if (carousel) {
                        carousel.update(featureBuilding[0].properties['楼栋照片'].split(';'), 200, 200);
                        buildingImgContainer.appendChild(carousel.domContainer);
                    } else {
                        carousel = new Carousel(featureBuilding[0].properties['楼栋照片'].split(';'), 200, 200);
                        buildingImgContainer.appendChild(carousel.domContainer);
                    }
                }

            } else {
                buildingImgContainer.innerHTML = '<span class=\"noimg-big\">暂无图片</span>';
            }
            buildingUnitContainer.innerHTML = getUnitImg(buildingUnit[featureBuilding[0].properties['楼栋ID']]);

            bulidingDetail.style.display = 'block';
            map.setFilter('buildingIconSelect', ['==', '楼栋ID', featureBuilding[0].properties['楼栋ID']]);
            map.flyTo({
                center: featureBuilding[0].properties.coordinates.split(','),
                zoom: 17
            });
        } else {
            bulidingDetail.style.display = 'none';
            map.setFilter('buildingIconSelect', ['==', '楼栋ID', '']);
        }
    });

    filterEl.addEventListener('keyup', function (e) {
        detailEl.style.display = 'none';
        bulidingDetail.style.display = 'none';
        var value = normalize(e.target.value);

        var filtered = districtGeojson.features.filter(function (feature) {
            var name = normalize(feature.properties['楼盘主名']);
            var code = normalize(feature.properties['楼盘别名']) || undefined;
            return value && (name.indexOf(value) > -1 || (code && code.indexOf(value) > -1));
        });

        renderListings(filtered);
    });
}

function normalize(string) {
    return string.trim().toLowerCase();
}

function renderListings(features) {
    listingEl.innerHTML = '';
    if (features.length) {
        features.forEach(function (feature) {
            var item = document.createElement('a');
            item.innerHTML = feature.properties['楼盘主名'] + (feature.properties['楼盘别名'] ? '<br />(' + feature.properties['楼盘别名'] + ')' : '');
            item.addEventListener('mousedown', function () {
                // detailEl.innerHTML = '<p class=\'detail-mainName\'>' + feature.properties['楼盘主名'] + '</p>' +
                //                  (feature.properties['楼盘别名'] ? '<p class=\'detail-subName\'>' + feature.properties['楼盘别名'] + '</p>' : '') +
                //                  (feature.properties['行政区'] ? '<p class=\'detail-area\'>' + feature.properties['行政区'] + '</p>' : '') +
                //                  (feature.properties['门牌号码'] ? '<p class=\'detail-adress\'>' + feature.properties['门牌号码'] + '</p>' : '');
                detailMainName.innerHTML = feature.properties['楼盘主名'];
                if (feature.properties['楼盘别名']) {
                    detailSubName.innerHTML = feature.properties['楼盘别名'];
                    detailSubName.style.display = 'block';
                } else {
                    detailSubName.style.display = 'none';
                }
                if (feature.properties['行政区']) {
                    detailArea.innerHTML = feature.properties['行政区'];
                    detailArea.style.display = 'inline-block';
                } else {
                    detailArea.style.display = 'none';
                }
                if (feature.properties['门牌号码']) {
                    detailAddress.innerHTML = feature.properties['门牌号码'];
                    detailAddress.style.display = 'inline-block';
                } else {
                    detailAddress.style.display = 'none';
                }

                listingEl.style.display = 'none';
                detailEl.style.display = 'block';

                map.flyTo({
                    center: feature.properties.coordinates.split(','),
                    zoom: 17
                });
                selectId = feature.properties['楼盘ID'];
                map.setFilter('districtPolygonSelected', ['==', '楼盘ID', feature.properties['楼盘ID']]);
                map.setFilter('buildingIcon', ['==', '楼栋所属楼盘ID', feature.properties['楼盘ID']]);
            });

            listingEl.appendChild(item);
        });
    } else if (filterEl.value) {
        var empty = document.createElement('p');
        empty.textContent = '未搜索到该小区';
        listingEl.appendChild(empty);
    }
    listingEl.style.display = 'block';
}

function getUnitImg(arr) {
    if (arr) {
        var str = '';
        for (var i = 0; i < arr.length; i++) {
            str = str + '<div class=\'unit\'>' +
                (arr[i]['单元照片'] ? '<img width=60 src=' + arr[i]['单元照片'].split(';')[0] + '>' : '<span class=\"noimg\">暂无图片</span>') +
                '<p class=\'unit-name\'>' +
                arr[i]['单元主名称'] +
                '</p>' +
                '<p class=\'unit-layer\'>总层数: ' + arr[i]['总层数'] + '</p>' +
                '<p class=\'unit-homes\'>每层户数: ' + arr[i]['每层户数'] + '</p>' +
                '</div>'
        }
        return str;
    } else {
        return ''
    }
}

function Carousel(urlArr, width, height) {
    this.urlArr = urlArr;
    this.imgWidth = width;
    this.imgHeight = height;
    this.domContainer = document.createElement('div');
    this.domContainer.className = 'carousel-container';

    this.domList = document.createElement('div');
    this.domList.className = 'carousel-list';
    this.domList.style.left = 0;
    this.domList.style.width = this.urlArr.length * 100 + '%';

    this.buttomList = document.createElement('div');
    this.buttomList.className = 'carousel-buttons';
    this.buttomList.style.left = (this.imgWidth - 80) / 2 + 'px';

    this.buttoms = [];

    this.urlArr.forEach(function (element, index) {
        var domImg = document.createElement('img');
        domImg.src = element;
        domImg.alt = index;
        domImg.width = this.imgWidth;
        domImg.height = this.imgHeight;
        domImg.style.width = this.imgWidth;
        domImg.style.height = this.imgHeight;
        this.domList.appendChild(domImg);

        var domButtom = document.createElement('span');
        domButtom.index = index;
        if (index === 0) domButtom.className = 'on';
        this.buttoms.push(domButtom);
        this.buttomList.appendChild(domButtom);
    }, this);

    this.domContainer.appendChild(this.domList);
    this.domContainer.appendChild(this.buttomList);

    this.left = document.createElement('a');
    this.left.innerHTML = '&lt;';
    this.left.className = 'carousel-arrow carousel-prev';
    this.left.style.top = (this.imgHeight - 23) / 2 + 'px';
    this.right = document.createElement('a');
    this.right.innerHTML = '&gt;';
    this.right.className = 'carousel-arrow carousel-next';
    this.right.style.top = (this.imgHeight - 23) / 2 + 'px';

    this.domContainer.appendChild(this.left);
    this.domContainer.appendChild(this.right);

    this.index = 0;
    this.left.onclick = this.goPrev.bind(this);
    this.right.onclick = this.goNext.bind(this);
}

Carousel.prototype.goPrev = function () {
    if (this.index > 0) {
        this.index -= 1;
    }
    this.buttonsShow();
    this.animate(this.imgWidth);
}
Carousel.prototype.goNext = function () {
    if (this.index < this.urlArr.length - 1) {
        this.index += 1;
    }
    this.buttonsShow();
    this.animate(-this.imgWidth);
}

Carousel.prototype.buttonsShow = function () {
    for (var i = 0; i < this.buttoms.length; i++) {
        if (this.buttoms[i].className == 'on') {
            this.buttoms[i].className = '';
        }
    }
    this.buttoms[this.index].className = 'on';
}

Carousel.prototype.animate = function (offset) {
    var newLeft = parseInt(this.domList.style.left) + offset;
    if (newLeft <= 0 && newLeft > -(this.urlArr.length * this.imgWidth)) {
        this.domList.style.left = newLeft + 'px';
    }
}

Carousel.prototype.update = function (urlArr, width, height) {
    this.urlArr = urlArr;
    this.imgWidth = width;
    this.imgHeight = height;

    this.index = 0;
    this.buttoms = [];
    this.domList.style.left = 0;
    this.domList.innerHTML = '';
    this.buttomList.innerHTML = '';

    this.urlArr.forEach(function (element, index) {
        var domImg = document.createElement('img');
        domImg.src = element;
        domImg.alt = index;
        domImg.width = this.imgWidth;
        domImg.height = this.imgHeight;
        domImg.style.width = this.imgWidth;
        domImg.style.height = this.imgHeight;
        this.domList.appendChild(domImg);

        var domButtom = document.createElement('span');
        domButtom.index = index;
        if (index === 0) domButtom.className = 'on';
        this.buttoms.push(domButtom);
        this.buttomList.appendChild(domButtom);
    }, this);
}